package com.isunland.managesystem.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.HashMap;
import java.util.UUID;
import org.json.JSONException;

/**
 * 添加办公申请
 *
 * @author wu
 */
public class WorkRequestAddFragment extends WorkRequestBaseFragment {

  protected Object volleyPostSave;

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // 设置返回图标
    setBack(true);
   setTitleCustom(R.string.addWorkRequest);

  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_save_submit, menu);
    menu.getItem(1).setTitle(R.string.saveAndSubmit);
    super.onCreateOptionsMenu(menu, inflater);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      // 响应返回图标
      case android.R.id.home:

        if (NavUtils.getParentActivityName(getActivity()) != null) {
          NavUtils.navigateUpFromSameTask(getActivity());
        }
        break;

      case R.id.menu_item_save:
        if (TextUtils.isEmpty(mRequestIntroduction_workRequest.getText().toString().trim())) {
          ToastUtil.show(R.string.completerequestConstruction);
        } else if (MyUtils.isEmptyText(mCompleteTime_workRequest)) {
          ToastUtil.show(R.string.completeMusttimeWorkRequest);
        } else if (MyUtils.isEmptyText(mCorporator_WorkRequest)) {
          ToastUtil.show(R.string.mustCorporator);
        } else {
          AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
          dialog.setTitle(R.string.restart_title);
          dialog.setMessage(R.string.ifSave);
          dialog.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {

            @Override public void onClick(DialogInterface dialog, int which) {
              volleyPostSave();
            }
          });

          dialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

            @Override public void onClick(DialogInterface dialog, int which) {
              dialog.dismiss();
            }
          });
          dialog.create().show();
        }
        break;
      //启动流程
      case R.id.menu_item_submit:

        if (TextUtils.isEmpty(mRequestIntroduction_workRequest.getText().toString().trim())) {
          ToastUtil.show(R.string.completerequestConstruction);
        } else if (MyUtils.isEmptyText(mCompleteTime_workRequest)) {
          ToastUtil.show(R.string.completeMusttimeWorkRequest);
        } else if (MyUtils.isEmptyText(mCorporator_WorkRequest)) {
          ToastUtil.show(R.string.mustCorporator);
        } else {
          AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
          dialog.setTitle(R.string.restart_title);
          dialog.setMessage(R.string.ifSureStart);
          dialog.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {

            @Override public void onClick(DialogInterface dialog, int which) {
              volleyPostSubmit();
            }
          });

          dialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

            @Override public void onClick(DialogInterface dialog, int which) {
              dialog.dismiss();
            }
          });
          dialog.create().show();
        }
        break;
      default:
        break;
    }
    return super.onOptionsItemSelected(item);
  }

  protected void volleyPostSave() {
    MyUtils.showDialogLoading(getActivity(), R.string.loadingSave);
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_SAVE_WORKREQUEST);
    HashMap<String, String> params = new HashMap<>();
    params.put("cooperateManId", mRegistjobNos);
    params.put("cooperateManName", mCorporator);
    params.put("cooperateDetails", mRequestIntroduction_workRequest.getText().toString().trim());
    params.put("finishTime", mCompleteTime_workRequest.getText().toString().trim());
    params.put("memberCode", mCurrentUser.getMemberCode());
    params.put("memberName", mCurrentUser.getMemberName());
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        SuccessMessage success = new Gson().fromJson(arg0, SuccessMessage.class);
        String resutl = success.getResult();
        String messageDetail = success.getMessage();
        if (SuccessMessage.SUCCESS.equalsIgnoreCase(resutl)) {
          ToastUtil.show(R.string.save_success);
          MyUtils.dismissDialog();
          getActivity().setResult(Activity.RESULT_OK);
          getActivity().finish();
        }

        if (SuccessMessage.FAILURE.equalsIgnoreCase(resutl)) {
          ToastUtil.show(messageDetail);
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        ToastUtil.show(R.string.save_failure);
      }
    });
  }

  /**
   * 保存并启动流程
   */
  private void volleyPostSubmit() {
    MyUtils.showDialogLoading(getActivity(), R.string.loadingStart);
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_START_WORKREQUEST);
    HashMap<String, String> params = new HashMap<>();
    params.put("id", UUID.randomUUID().toString());
    params.put("cooperateManId", mRegistjobNos);
    params.put("cooperateManName", mCorporator);
    params.put("cooperateDetails", mRequestIntroduction_workRequest.getText().toString().trim());
    params.put("finishTime", mCompleteTime_workRequest.getText().toString().trim());
    params.put("memberCode", mCurrentUser.getMemberCode());
    params.put("memberName", mCurrentUser.getMemberName());
    params.put("dataStatus", "waitCheck");
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        try {
          SuccessMessage message = new Gson().fromJson(arg0, SuccessMessage.class);
          String result = message.getResult();
          String messages = message.getMessage();
          if (SuccessMessage.SUCCESS.equalsIgnoreCase(result)) {
            ToastUtil.show(R.string.startFolwSuccess);
            MyUtils.dismissDialog();
            getActivity().setResult(Activity.RESULT_OK);
            getActivity().finish();
          } else {
            ToastUtil.show(messages);
          }
        } catch (Exception e) {
          MyUtils.show(getActivity(), R.string.startFolwFail);
          LogUtil.e("startError", e);
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        ToastUtil.show(R.string.startFolwFail);
      }
    });
  }
}
